package com.flute.icrawler.app.distributed;

import java.io.Serializable;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.client.Constants;
import com.flute.haflute.jobbox.base.CloudTask;
import com.flute.haflute.jobbox.base.InputResource;
import com.flute.haflute.jobbox.base.StatusReporter;
import com.flute.icrawler.app.task.entity.CrawlTask;
import com.flute.icrawler.config.CrawlConfigUtil;
import com.flute.icrawler.framework.framework.ICrawlUrlPool;
import com.flute.icrawler.framework.framework.JobChildController;

public class DistributedJobController4Child implements CloudTask {
	private JobChildController crawlJobController = null;
	private ICrawlUrlPool uniformRemoteCrawlUrlPool = null;

	private static Logger logger = LoggerFactory
			.getLogger(DistributedJobController4Child.class);

	private String crawlJobCfgfile = "";

	public DistributedJobController4Child() {
	}

	@Override
	public void start(StatusReporter reporter) throws RemoteException {
		if (crawlJobController != null) {
			// start storage added on 2010.8.13

			crawlJobController.start();
		}

	}

	@Override
	public void end() throws RemoteException {
		// do nothing for crawler framework
	}

	@Override
	public void setInput(InputResource inputResource) throws RemoteException {
		System.out.println("hello kitty");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void configureTask(Serializable config) throws RemoteException {
		if (config instanceof Properties) {
			Properties props = (Properties) config;
			Iterator ite = props.keySet().iterator();
			while (ite.hasNext()) {
				String key = (String) ite.next();
				if (key.startsWith(Constants.FILEPREFIX
						+ CrawlTask.CONFIG_FILENAME)) {
					crawlJobCfgfile = props.getProperty((String) key);
				}
			}
			logger.info("fileName=" + crawlJobCfgfile);
			crawlJobController = new JobChildController(
					uniformRemoteCrawlUrlPool, CrawlConfigUtil
							.newCrawlConfig(crawlJobCfgfile));
		}
	}

	/*
	 * @see com.cpkf.yyjd.cloud.base.CloudTask#configJobAgent(java.rmi.Remote)
	 */
	@Override
	public void configJobAgent(Remote agent) throws RemoteException {
		if (agent instanceof ICrawlUrlPool) {
			// uniformRemoteCrawlUrlPool是一个全局的IntervalCrawlUrlPool远程对象
			uniformRemoteCrawlUrlPool = (ICrawlUrlPool) agent;
		}
	}

}
